package com.goddess.yeecolor.fragment.MyCollectionFragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.goddess.yeecolor.Modle.ActivityFragmentModle;
import com.goddess.yeecolor.R;
import com.goddess.yeecolor.activity.LoginAcitivity;
import com.goddess.yeecolor.adapter.VideoFragmentAdapter;
import com.goddess.yeecolor.base.BaseFragment;
import com.goddess.yeecolor.tools.LogUtils;
import com.goddess.yeecolor.tools.MyUrl;
import com.goddess.yeecolor.tools.OkttpUtils;
import com.goddess.yeecolor.tools.SharePreceUtils;
import com.goddess.yeecolor.tools.ToastUtils;
import com.goddess.yeecolor.view.dialog_progress;
import com.goddess.yeecolor.webview.CurriculumFragmentWebView;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者: CaoJunping
 * 时间: 2017/1/16
 * 作用: ******
 * 备注: 我的Fragmnet个人收藏Activity 视频Fragment
 */
public class VideoFragment extends BaseFragment {
    private XRecyclerView recyclerView;
    private VideoFragmentAdapter adapter;
    private List<ActivityFragmentModle> modles=new ArrayList<ActivityFragmentModle>();
    private LinearLayoutManager manager;
    private int lomode;
    private View mView;
    //记录分页 页数
    private int page=1;
    //记录上拉下拉状态
    private String PULL_STATE="";
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(mView==null){
            mView=LayoutInflater.from(getContext()).inflate(R.layout.fragment_video,container,false);
            initFindView();
            initOnClck();
            initdatas();
        }
        return mView;
    }

    public void initdatas(){
        setProgress();
        PULL_STATE="STATE";
        initData();
    }
    private dialog_progress dialog_progress;
    private void setProgress(){
        dialog_progress=new dialog_progress(getActivity());
        dialog_progress.requestWindowFeature(Window.FEATURE_NO_TITLE);

        dialog_progress.setCanceledOnTouchOutside(false);//按返回键可以关闭进度条
        dialog_progress.show();
    }
    @Override
    public void initOnClck() {

        /**
         * 下拉刷新&下拉加载
         */
        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            /**
             * 下拉刷新
             */
            @Override
            public void onRefresh() {
                PULL_STATE="BOMOOT";
                page=1;
                if(adapter!=null){
                    modles.clear();
                    adapter.clear();
                    adapter.notifyDataSetChanged();
                }
                initData();
            }
            /**
             * 上拉加载
             */
            @Override
            public void onLoadMore() {
                PULL_STATE="TOP";
                page++;
                initData();

            }
        });

        /**
         *
         * item点击事件
         */
        adapter.setOnItemClicklistener(new VideoFragmentAdapter.OnItemClicklistener() {
            @Override
            public void OnItemClick(View view, int position) {
                String uuid= SharePreceUtils.getOther("user","unique");
                if(!"".equals(uuid)){
                    if(String.valueOf(modles.get(position).getEventsid()).equals("")){
                        ToastUtils.toast("该课程不存在!");
                        Log.e(MyUrl.TAG,"ididididi"+modles.get(position).getEventsid()+"position"+position);
                    }else{
                        Intent intent=new Intent();
                        intent.setClass(getActivity(),CurriculumFragmentWebView.class);
                        intent.putExtra("id",String.valueOf(modles.get(position).getEventsid()));
                        intent.putExtra("webview",modles.get(position).getWebview());
                        intent.putExtra("price",modles.get(position).getPrice());
                        Log.e(MyUrl.TAG,"ididididi"+modles.get(position).getId()+"position"+position);
                        startActivity(intent);
                    }
                }else{
                    Intent intent=new Intent(getContext(),LoginAcitivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void initFindView() {

        recyclerView= (XRecyclerView) mView.findViewById(R.id.feagment_video_recyclerview);
        manager=new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(manager);
        recyclerView.setPullRefreshEnabled(false);
        /**
         * 设置上拉 下拉 样式
         */
        recyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        recyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        recyclerView.setArrowImageView(R.mipmap.ic_pulltorefresh_arrow);
        View view= LayoutInflater.from(getActivity()).inflate(R.layout.empty,null);
        recyclerView.setEmptyView(view);
        adapter=new VideoFragmentAdapter(getContext(),modles);
    }
    @Override
    public void initData() {

        //初始化实体类数据
        setRequest();
    }
    private void setRequest(){
        Map<Object,Object> map=new HashMap<>();
        map.put("typed", MyUrl.TYPEC);//活动
        map.put("unique", SharePreceUtils.getOther("user","unique"));
        map.put("page",page+"");
        OkttpUtils.getIntence().OkttpPost(MyUrl.COLLECTGETLIST,map,handler,1);
        LogUtils.getInstence().info(MyUrl.COLLECTGETLIST+"?typed="+MyUrl.TYPEC+"&unique="+SharePreceUtils.getOther("user","unique")+"&page="+page);
//        setProgress();
    }
    private String jsonString;
    private int code;

    private String price,title;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                jsonString=msg.getData().getString("result");
                JSONObject object=new JSONObject(jsonString);
                code=object.getInt("code");
                if (code==100){
                    Log.e(MyUrl.TAG,jsonString);
                    if (object.has("result")) {
                        JSONArray result = object.getJSONArray("result");
                        for (int i = 0; i < result.length(); i++) {
                            JSONObject itemdata = result.getJSONObject(i);
                            ActivityFragmentModle info = new ActivityFragmentModle();
                            info.setId(itemdata.getInt("id"));
                            info.setUnique(itemdata.getString("unique"));
                            info.setTyped(itemdata.getString("typed"));
                            info.setCollection_id(itemdata.getInt("collection_id"));
                            info.setAddtime(itemdata.getString("addtime"));
                            info.setPeople(itemdata.getInt("people"));
                            info.setViews(itemdata.getInt("views"));

                            JSONObject events = itemdata.getJSONObject("events");
                            info.setEventsid(events.optString("id"));
                            info.setTitle(events.optString("title"));
                            info.setStatae(events.optInt("state"));
                            info.setThumb(events.optString("thumb"));
                            info.setPrice(events.optString("price"));
                            info.setInfo(events.optString("info"));
                            info.setTech(events.optString("tech"));
                            info.setWebview(events.optString("webview"));
                            modles.add(info);
                        }
                    } else {
                        JSONObject extend=object.getJSONObject("extends");
                        if (extend.getString("endfull").equals("0")){

                        }
                    }
                } else {
                    JSONObject extend=object.getJSONObject("extends");
                    if (extend.getString("endfull").equals("0")){
                        ToastUtils.toast("暂无数据");
                    }
                }
                if(PULL_STATE.equals("BOMOOT")){
                    recyclerView.refreshComplete();
                }else if(PULL_STATE.equals("TOP")){
                    recyclerView.loadMoreComplete();
                }else{
                    /**
                     * 适配器
                     */
                    if (dialog_progress.isShowing()){
                        dialog_progress.dismiss();
                    }
                    recyclerView.setAdapter(adapter);
                    recyclerView.setRefreshing(true);

                }
                adapter.notifyDataSetChanged();

                recyclerView.setPullRefreshEnabled(true);
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();

    }
}
